import os, urllib
from rer import Categories, get_sign_link
from google.appengine.api import users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class ShowData(webapp.RequestHandler):
    def get(self):
        categories = Categories.all().order('index')
        data_list = []
        
        for category in categories:
            items = db.GqlQuery("SELECT * FROM SampleData WHERE category = :1", category.key())
            data_list.append({ 'category':category, 'items':items })
        
        current = self.request.get('cr')
        res = {'sub_title'       : 'JavaScript RegExp Quick Reference',
               'data'            : data_list,
               'categories'      : categories,
               'current'         : urllib.unquote(current) if current else '',
               'content_template': 'content.reference.' + ('admin' if users.is_current_user_admin() else 'none') + '.html'}
        
        for k, v in get_sign_link(self.request.uri).iteritems(): res[k] = v
        
        path = os.path.join(os.path.dirname(__file__), 'template', 'reference.html')
        self.response.out.write( template.render(path,res) )


application = webapp.WSGIApplication([('/reference', ShowData)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()